﻿#include "ScissorStack.h"

static ScissorStack *s_scissorStack = nullptr;

ScissorStack* ScissorStack::getInstance()
{
	if (!s_scissorStack)
	{
		s_scissorStack = new ScissorStack();
	}
	return s_scissorStack;
}


void ScissorStack::push(const Rect& rect)
{
	if (_stack.size())
	{
		// 交集
		rect.unionWithRect(_stack.top());
	}

	if (_stack.size())
	{
		asert(Director::getInstance()->getOpenGLView()->isScissorEnabled(), "GLView must be ScissorEnabled");
	}

	else
	{
		_isEnabled = cocos2d::Director::getInstance()->getOpenGLView()->isScissorEnabled();
		if (!_isEnabled)
		{
#ifdef ccc_use_engine_g2d
#else
			glEnable(GL_SCISSOR_TEST);
#endif
		}
	}
	_stack.push(rect);
	cocos2d::Director::getInstance()->getOpenGLView()->setScissorInPoints(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
}



void ScissorStack::pop()
{
	asert(_stack.size(), "ScissorStack, push and pop must be a pairs");
	_stack.pop();
	if (_stack.empty())
	{
#ifdef ccc_use_engine_g2d
		cocos2d::Director::getInstance()->getOpenGLView()->setScissorInPoints(0, 0, 0, 0);
#else
		if (!_isEnabled)
		{
			glDisable(GL_SCISSOR_TEST);
		}
#endif
	}
	else 
	{
		cocos2d::Rect rect = _stack.top();
		cocos2d::Director::getInstance()->getOpenGLView()->setScissorInPoints(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
	}
}
